package com.robcity.platform.application;

/**
 * @Description
 * @Author zhangsong
 * @Date 2024/8/29
 **/
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

@Component
public class UdpClientServiceApplication implements DisposableBean {


    private NioEventLoopGroup group;
    private Channel channel;

    public UdpClientServiceApplication() {
        // 初始化 NioEventLoopGroup 和 Channel
        group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            // 这里可以添加其他的处理器
                        }
                    });

            channel = bootstrap.bind(0).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sendUdpMessage(String message,String host,Integer port) {
        try {
            InetSocketAddress address = new InetSocketAddress(host, port);
            DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8), address);
            ChannelFuture future = channel.writeAndFlush(packet).sync();

            if (future.isSuccess()) {
                System.out.println("Message sent successfully!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() throws Exception {
        // 关闭资源
        if (channel != null) {
            channel.close().sync();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
